package im.xz.cn.xiaip;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.ServerListPingEvent;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class ping implements Listener {
    private boolean isInternalIp(String ip) {
        if (ip == null || ip.isEmpty()) return false;
        String[] parts = ip.split("\\.");
        if (parts.length != 4) return false;
        try {
            int part0 = Integer.parseInt(parts[0]);
            int part1 = Integer.parseInt(parts[1]);
            if (part0 == 10) return true;
            else if (part0 == 172 && part1 >= 16 && part1 <= 31) return true;
            else if (ip.equals("127.0.0.1")) return true;
            else return part0 == 192 && part1 == 168;
        } catch (NumberFormatException e) {
            return false;
        }
    }
    @EventHandler
    public void onPing(ServerListPingEvent event) throws IOException, InterruptedException {
        String ip = event.getAddress().getHostAddress();
        boolean isInternal = isInternalIp(ip);
        if (!isInternal) {
            String url = "https://opendata.baidu.com/api.php?query=" + ip + "&co=&resource_id=6006&oe=utf8";

            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .build();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            JsonObject jsonResponse = JsonParser.parseString(response.body()).getAsJsonObject();
            JsonArray dataArray = jsonResponse.getAsJsonArray("data");
            JsonObject firstDataObject = dataArray.get(0).getAsJsonObject();
            String location = firstDataObject.get("location").getAsString();
            System.out.println(ip + "(" + location + ") Ping了服务器");
        }
    }
}
